#include <gnuplotter.h>


int parseargs( int argc, char ** argv, options_t * options ) {
	int i, test;
	char mode;

	//if no args, we're dead
	if ( (argc-1) == 0 ) return -1;

	//check arguments one by one
	i=0;
	while ( i < argc-1 ) {
		if (!strncmp(argv[i],"-",1)) { //check for -s, -o, -t
			mode = argv[i++][1];
		}
		else
			return -1;
		//now we have the mode stored to char mode
		switch (mode) {
			case 'w': //read in window size options
				if ( i+2 > argc-1 ) return -1; //are there enough args left?
				if ( 1 != sscanf(argv[i++], "%d", &(options->geometry[0]))) return -1;
				if ( 1 != sscanf(argv[i++], "%d", &(options->geometry[1]))) return -1;
				if ( options->geometry[0] <= 0 || options->geometry[1] <= 0 ) return -1;
				break;
			case 'o': //set output file
				if ( i+1 > argc-1 ) return -1; //are there enough args left?
				if ( 1 != sscanf(argv[i++], "%s", options->outname) ) return -1;
				options->outfile=fopen(options->outname,"w");
				checkfileptr(options->outfile,options->outname,options);
				break;
			case 't': //what type of plot
				if ( i+1 > argc-1 ) return -1; //are there enough args left?
				if ( !strncmp(argv[i],"points", 6) ) { options->withtype = points; }
				else if ( !strncmp(argv[i],"pm3d", 4) ) { options->withtype = pm3d; }
				else if ( !strncmp(argv[i],"lines", 5) ) { options->withtype = lines; }
				else if ( !strncmp(argv[i],"dots", 4) ) { options->withtype = dots; }
				else if ( !strncmp(argv[i],"heat", 4) ) { options->withtype = heat; }
				else return -1;
				i++;
				break;
			case 'g': //grid dimension
				if ( i+2 > argc-1) return -1;
				if ( 1 != sscanf(argv[i++], "%d", &(options->griddim[0]))) return -1;
				if ( 1 != sscanf(argv[i++], "%d", &(options->griddim[1]))) return -1;
				if ( options->griddim[0] <= 0 || options->griddim[1] <= 0 ) return -1;
				break;
			case 's': //grid sigma
				if ( i+2 > argc-1) return -1;
				if ( 1 != sscanf(argv[i++], "%lf", &(options->gridsigma[0]))) return -1;
				if ( 1 != sscanf(argv[i++], "%lf", &(options->gridsigma[1]))) return -1;
				if ( options->gridsigma[0] <= 0 || options->gridsigma[1] <= 0 ) return -1;
				break;
			default:
				return -1;
		}
	}
	
	return 0;
}

void setdefaults(options_t * o) {
	//set default window geometry
	if ( o->geometry[0] == 0 ) o->geometry[0]=1024;
	if ( o->geometry[1] == 0 ) o->geometry[0]=768;

	//set default plot type
	if ( o->withtype == 0 ) o->withtype=points;

	//if output file isn't set, we are in interactive mode
	if ( ! o->outfile ) o->interactive=1;

	//is grid dimension set?
	if ( o->griddim[0] == 0 ) o->griddim[0]=256;
	if ( o->griddim[1] == 0 ) o->griddim[0]=256;

	return;
}
